/**
 * 
 */
package xyz.zhengtank.grpc.server;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;
import xyz.zhengtank.grpc.service.HelloProtoServiceImpl;

/**
 * @author tank
 * @since 2018-03-30
 * @category 
 * 
 */
public class HelloProtoServer {
	
	private static final Logger LOG =  LoggerFactory.getLogger(HelloProtoServer.class);
	
	private Server server;
	
	/**
	 * 启动gRPC服务器
	 * @throws IOException
	 */
	private void start() throws IOException {
		
		/*服务运行的端口*/
		int port = 50051;
		server = NettyServerBuilder.forPort(port)
				.addService(new HelloProtoServiceImpl())
				.build()
				.start();
		LOG.info("Server running at " + port);
		Runtime.getRuntime().addShutdownHook(new Thread(){

			@Override
			public void run() {
				System.out.println("*** shutting down gRPC server since JVM is shutting down");
				HelloProtoServer.this.stop();
				System.out.println("*** server shut down");
			}
			
		});
	}
	
	/**
	 * 关闭gRPC服务器
	 */
	private void stop() {
		if(server!=null) {
			server.shutdown();
		}
	}
	
	/**
	 * 由于grcp库使用后台线程运行的方式，所以在main主线程里等待终止线程
	 * @throws InterruptedException
	 */
	private void blockUntilShutdown() throws InterruptedException {
		if(server != null) {
			server.awaitTermination();
		}
	}
	
	public static void main(String[] args) throws InterruptedException, IOException {
		final HelloProtoServer server = new HelloProtoServer();
		server.start();
		server.blockUntilShutdown();
	}

}
